package com.xbts.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.constant.UserConstants;
import com.xbts.common.core.domain.model.LoginUser;
import com.xbts.common.utils.SnowFlakeUtil;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.CnCloudMarketSku;
import com.xbts.system.domain.dto.CnCloudMarketSkuDTO;
import com.xbts.system.domain.vo.CnCloudMarketUserVO;
import com.xbts.system.domain.vo.CnCloudMarketVO;
import com.xbts.system.service.ICnCloudMarketSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbts.system.mapper.CnCloudMarketMapper;
import com.xbts.system.domain.CnCloudMarket;
import com.xbts.system.service.ICnCloudMarketService;
import com.xbts.common.utils.DateUtils;
import com.xbts.common.utils.SecurityUtils;

/**
 * 云市场Service业务层处理
 *
 * @author xbts
 * @date 2023-08-22
 */
@Service
public class CnCloudMarketServiceImpl extends ServiceImpl<CnCloudMarketMapper, CnCloudMarket> implements ICnCloudMarketService {

    @Autowired
    private ICnCloudMarketSkuService cnCloudMarketSkuService;
    @Autowired
    private CnCloudMarketMapper cnCloudMarketMapper;

    /**
     * 查询云市场列表
     *
     * @param cnCloudMarket 云市场
     * @return 云市场
     */
    @Override
    public List<CnCloudMarket> selectCnCloudMarketList(CnCloudMarket cnCloudMarket) {
        QueryWrapper<CnCloudMarket> queryWrapper = cnCloudMarket.queryWrapper();
        // 关键字搜索
        if (StringUtils.isNotEmpty(cnCloudMarket.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like("intro", cnCloudMarket.getSearchValue())
                    .or().like("description", cnCloudMarket.getSearchValue())
                    .or().like("title", cnCloudMarket.getSearchValue()));
        }
        if(!SecurityUtils.isManager()) {
            queryWrapper.isNotNull("lowest_price");
            queryWrapper.ge("lowest_price", 0);
        }
        Map<String, Object> params = cnCloudMarket.getParams();

        if(StringUtils.isNotNull(params.get("sortField"))) {
            if (((String) params.get("sortField")).equalsIgnoreCase("price")) {
                if("asc".equals(params.get("sort"))) {
                    queryWrapper.orderByAsc("lowest_price");
                } else {
                    queryWrapper.orderByDesc("lowest_price");
                }
            } else {
                if("asc".equals(params.get("sort"))) {
                    queryWrapper.orderByAsc("create_time");
                } else {
                    queryWrapper.orderByDesc("create_time");
                }
            }
        } else {
            queryWrapper.orderByDesc("create_time");
        }

        return cnCloudMarketMapper.selectCnCloudMarketList(queryWrapper);
    }

    /**
     * 查询云市场
     *
     * @param id 云市场主键
     * @return 云市场
     */
    @Override
    public CnCloudMarket selectCnCloudMarketById(String id) {
        CnCloudMarketVO cnCloudMarketVO = new CnCloudMarketVO();
        CnCloudMarket cnCloudMarket = getById(id);
        if (cnCloudMarket == null) {
            return null;
        }
        BeanUtils.copyProperties(cnCloudMarket, cnCloudMarketVO);

        // 查询云市场规格
        LambdaQueryWrapper<CnCloudMarketSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CnCloudMarketSku::getMarketId, id);
        queryWrapper.eq(CnCloudMarketSku::getDeleteFlag, false);
        queryWrapper.orderByAsc(CnCloudMarketSku::getPrice);
        List<CnCloudMarketSku> cnCloudMarketSkuList = cnCloudMarketSkuService.list(queryWrapper);

        if (!cnCloudMarketSkuList.isEmpty()) {
            cnCloudMarketVO.setLowerPriceProduct(cnCloudMarketSkuList.get(0));
            // 价钱最低那那一条记录的购买方式
            List<String> buyingMethods = cnCloudMarketSkuList.stream()
                    .distinct()
                    .filter(f -> f.getFirstSkuName().equals(cnCloudMarketVO.getLowerPriceProduct().getFirstSkuName()))
                    .map(CnCloudMarketSku::getCloudMarketBuyingMethod)
                    .collect(Collectors.toList());
            cnCloudMarketVO.getLowerPriceProduct().setCloudMarketBuyingMethod(String.join(",", buyingMethods));
        }

        return cnCloudMarketVO;
    }

    /**
     * 新增云市场
     *
     * @param cnCloudMarket 云市场
     * @return 结果
     */
    @Override
    public boolean insertCnCloudMarket(CnCloudMarketVO cnCloudMarket) {
        cnCloudMarket.setCreateBy(SecurityUtils.getUserId().toString());
        Long id = SnowFlakeUtil.getSnowFlakeId();
        cnCloudMarket.setMarketId(id);
        boolean save = save(cnCloudMarket);

        // 保存云市场规格
        if (!cnCloudMarket.getCnCloudMarketSkuList().isEmpty()) {
            for (CnCloudMarketSku cnCloudMarketSku : cnCloudMarket.getCnCloudMarketSkuList()) {
                cnCloudMarketSku.setMarketId(id);
            }
            cnCloudMarketSkuService.saveBatch(cnCloudMarket.getCnCloudMarketSkuList());
        }
        return save;
    }

    /**
     * 修改云市场
     *
     * @param cnCloudMarket 云市场
     * @return 结果
     */
    @Override
    public boolean updateCnCloudMarket(CnCloudMarketVO cnCloudMarket) {
        cnCloudMarket.setUpdateBy(SecurityUtils.getUserId().toString());
        cnCloudMarket.setUpdateTime(DateUtils.getNowDate());
        // 删除云市场规格
//        LambdaQueryWrapper<CnCloudMarketSku> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(CnCloudMarketSku::getMarketId, cnCloudMarket.getMarketId());
//        cnCloudMarketSkuService.remove(queryWrapper);
//        // 保存云市场规格
//        if (!cnCloudMarket.getCnCloudMarketSkuList().isEmpty()) {
//            cnCloudMarketSkuService.saveBatch(cnCloudMarket.getCnCloudMarketSkuList());
//        }
        return updateById(cnCloudMarket);
    }

    /**
     * 批量删除云市场
     *
     * @param ids 需要删除的云市场主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCnCloudMarketByIds(List<String> ids) {
        // 删除云市场规格
        LambdaUpdateWrapper<CnCloudMarketSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(CnCloudMarketSku::getMarketId, ids);
        updateWrapper.set(CnCloudMarketSku::getDeleteFlag, true);
        cnCloudMarketSkuService.update(updateWrapper);

        // 删除云市场
        LambdaUpdateWrapper<CnCloudMarket> marketLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        marketLambdaUpdateWrapper.in(CnCloudMarket::getMarketId, ids);
        marketLambdaUpdateWrapper.set(CnCloudMarket::getDeleteFlag, true);
        return update(marketLambdaUpdateWrapper);
    }

    /**
     * 删除云市场信息
     *
     * @param id 云市场主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean deleteCnCloudMarketById(String id) {
        return removeById(id);
    }

//    @Override
//    public List<CnCloudMarketSku> getFirstDirectory(String marketId) {
//        LambdaQueryWrapper<CnCloudMarketSku> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.select(CnCloudMarketSku::getFirstSkuName, CnCloudMarketSku::getMarketId)
//                .eq(CnCloudMarketSku::getMarketId, marketId)
//                .orderByAsc(CnCloudMarketSku::getPrice);
//        List<CnCloudMarketSku> cnCloudMarketSkuList = cnCloudMarketSkuService.list(queryWrapper);
//        List<CnCloudMarketSku> result = new ArrayList<>();
//
//        Map<String, String> temp = new HashMap<>();
//        // 按照价格排序，取价格最低的一个一级目录
//        for (CnCloudMarketSku cnCloudMarketSku : cnCloudMarketSkuList) {
//            String firstSkuName = cnCloudMarketSku.getFirstSkuName();
//            if (!temp.containsKey(firstSkuName)) {
//                temp.put(firstSkuName, firstSkuName);
//                result.add(cnCloudMarketSku);
//            }
//        }
//        return result;
//    }

    @Override
    public List<String> getFirstDirectory(String marketId) {
        LambdaQueryWrapper<CnCloudMarketSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CnCloudMarketSku::getFirstSkuName, CnCloudMarketSku::getMarketId)
                .eq(CnCloudMarketSku::getMarketId, marketId)
                .orderByAsc(CnCloudMarketSku::getPrice);
        List<CnCloudMarketSku> cnCloudMarketSkuList = cnCloudMarketSkuService.list(queryWrapper);
        List<String> result = new ArrayList<>();

        // 按照价格排序，取价格最低的一个一级目录
        for (CnCloudMarketSku cnCloudMarketSku : cnCloudMarketSkuList) {
            String firstSkuName = cnCloudMarketSku.getFirstSkuName();
            if (!result.contains(firstSkuName)) {
                result.add(firstSkuName);
            }
        }
        return result;
    }

    @Override
    public List<String> getNextDirectory(CnCloudMarketSku cnCloudMarketSku) {
        LambdaQueryWrapper<CnCloudMarketSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CnCloudMarketSku::getMarketId, cnCloudMarketSku.getMarketId());
        queryWrapper.eq(CnCloudMarketSku::getFirstSkuName, cnCloudMarketSku.getFirstSkuName());
        List<CnCloudMarketSku> cnCloudMarketSkuList = cnCloudMarketSkuService.list(queryWrapper);
        // 判断是否有二级目录
        if (cnCloudMarketSkuList.isEmpty()) {
            return null;
        }
        return cnCloudMarketSkuList.stream().filter(v -> StringUtils.isNotEmpty(v.getSecondSkuName())).map(CnCloudMarketSku::getSecondSkuName).distinct().collect(Collectors.toList());

//        if (StringUtils.isNotEmpty(cnCloudMarketSkuList.get(0).getSecondSkuName())) {
//            Map<String, List<CnCloudMarketSku>> listMap = cnCloudMarketSkuList
//                    .stream()
//                    .collect(Collectors.groupingBy(CnCloudMarketSku::getSecondSkuName, Collectors.mapping(value -> value, Collectors.toList())));
//            return getCnCloudMarketSkus(listMap);
//        } else {
//            Map<String, List<CnCloudMarketSku>> listMap = cnCloudMarketSkuList
//                    .stream()
//                    .collect(Collectors.groupingBy(CnCloudMarketSku::getFirstSkuName, Collectors.mapping(value -> value, Collectors.toList())));
//            return getCnCloudMarketSkus(listMap);
//        }
    }

    @Override
    public List<CnCloudMarketSku> getPurchaseMethod(CnCloudMarketSku cnCloudMarketSku) {
        return cnCloudMarketSkuService.list(new LambdaQueryWrapper<CnCloudMarketSku>()
                .eq(CnCloudMarketSku::getMarketId, cnCloudMarketSku.getMarketId())
                .eq(CnCloudMarketSku::getFirstSkuName, cnCloudMarketSku.getFirstSkuName())
                .eq(StringUtils.isNotEmpty(cnCloudMarketSku.getSecondSkuName()), CnCloudMarketSku::getSecondSkuName, cnCloudMarketSku.getSecondSkuName()));
    }

    @Override
    public BigDecimal priceCalculation(CnCloudMarketSkuDTO cnCloudMarketSku) {
        CnCloudMarketSku cloudMarketSku = cnCloudMarketSkuService.getById(cnCloudMarketSku.getMarketSkuId());
        if (cloudMarketSku != null) {
            BigDecimal price = cloudMarketSku.getPrice();
            BigDecimal num = new BigDecimal(cnCloudMarketSku.getNumber());
            return price.multiply(num);
        }
        return null;
    }

    @Override
    public List<CnCloudMarketUserVO> userBelongToList(String searchValue) {
        Long userId = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!loginUser.getUser().getUserType().equals(UserConstants.USER_TYPE_MANAGER)) {
            userId = SecurityUtils.getUserId();
        }
        return baseMapper.userBelongToList(searchValue, userId);
    }

    /**
     * 获取云市场规格
     *
     * @param listMap 云市场规格
     * @return
     */
    private Map<String, Object> getCnCloudMarketSkus(Map<String, List<CnCloudMarketSku>> listMap) {
        Map<String, Object> result = new HashMap<>();
        List<String> buyingMethod = new ArrayList<>();
        for (Map.Entry<String, List<CnCloudMarketSku>> stringListEntry : listMap.entrySet()) {
            List<CnCloudMarketSku> cloudMarketSkuList = stringListEntry.getValue();
            // 拼接购买方式
            buyingMethod = cloudMarketSkuList.stream()
                    .map(CnCloudMarketSku::getCloudMarketBuyingMethod)
                    .collect(Collectors.toList());
            result.put(stringListEntry.getKey(), cloudMarketSkuList);
        }
        // 设置购买方式
        result.put("cloudMarketBuyingMethod", buyingMethod);
        return result;
    }

}
